package com.example.demo.schedule;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.dao.GoodsDao;
import com.example.demo.dao.OrderDao;
import com.example.demo.entity.Goods;
import com.example.demo.entity.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 定时扫描超时未支付的订单
 */
@Component
public class OrderSchedule {

    @Autowired
    OrderDao orderDao;
    @Autowired
    GoodsDao goodsDao;

    @Scheduled(cron = "0 0/1 * * * ? ")
    public void scanTimeoutOrder() {

        //todo 暂时扫描所有订单，可优化
        Date now = new Date();
        List<Order> orders = orderDao.selectList(null);
        if (CollectionUtils.isEmpty(orders)) {
            return;
        }
        //查询状态为未支付的并且超过5分钟的
        List<Order> timeoutOrders = orders.stream().filter(i -> i.getStatus() == 1 && DateUtil.betweenMs(i.getCrtTime(), now) > 5 * 60 * 1000).collect(Collectors.toList());
        System.out.println("超时的未支付订单为" + timeoutOrders);

        if (CollectionUtils.isEmpty(timeoutOrders)) {
            return;
        }
        //todo 批量修改订单状态为超时未支付
        for (Order timeoutOrder : timeoutOrders) {
            orderDao.updateById(timeoutOrder.setStatus(3));
        }

        //根据商品id分组
        Map<String, List<Order>> map = timeoutOrders.stream().collect(Collectors.groupingBy(Order::getGoodsId));

        map.forEach((goodsId, list) -> {
            //根据超时未支付的订单量恢复相应商品的库存
            int size = list.size();
            Goods goods = goodsDao.selectById(goodsId);
            goods.setStock(goods.getStock() + size);
            goodsDao.updateById(goods);
        });


    }


}
